'use client'

import { useState } from 'react'
import { Form, Input, Button, Card, Typography, message, Divider, Checkbox } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { request } from '@/utils/request'
import { API_ENDPOINTS, STORAGE_KEYS } from '@/utils/constants'

const { Title, Text } = Typography

interface LoginForm {
  usernameOrEmail: string
  password: string
  remember: boolean
}

export default function LoginPage() {
  const [form] = Form.useForm()
  const [loading, setLoading] = useState(false)
  const router = useRouter()

  const onFinish = async (values: LoginForm) => {
    setLoading(true)
    try {
      const response = await request.post(API_ENDPOINTS.AUTH.LOGIN, {
        usernameOrEmail: values.usernameOrEmail,
        password: values.password
      })

      if (response.code === 200) {
        // 保存登录信息
        const { token, user } = response.data
        localStorage.setItem(STORAGE_KEYS.TOKEN, token)
        localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(user))
        
        message.success('登录成功！')
        
        // 按照用户类型跳转 - 首先检查userType是否存在
        if (user && user.userType) {
          if (user.userType === 'ADMIN') {
            router.push('/admin')
          } else {
            router.push('/products')
          }
        } else {
          // 如果没有userType，默认跳转到产品页面
          console.warn('User object missing userType property:', user)
          router.push('/products')
        }
      } else {
        message.error(response.message || '登录失败')
      }
    } catch (error: any) {
      message.error(error.message || '网络错误，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div style={{ 
      minHeight: '100vh', 
      background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      padding: '20px'
    }}>
      <Card style={{ width: '100%', maxWidth: '400px', boxShadow: '0 8px 24px rgba(0,0,0,0.12)' }}>
        <div style={{ textAlign: 'center', marginBottom: '30px' }}>
          <Title level={2} style={{ color: '#1890ff', marginBottom: '8px' }}>
            欢迎回来
          </Title>
          <Text type="secondary">
            登录您的账号
          </Text>
        </div>

        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          layout="vertical"
          requiredMark={false}
          initialValues={{ remember: true }}
        >
          <Form.Item
            name="usernameOrEmail"
            rules={[
              { required: true, message: '请输入用户名或邮箱' }
            ]}
          >
            <Input 
              prefix={<UserOutlined />} 
              placeholder="用户名或邮箱" 
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码' }
            ]}
          >
            <Input.Password 
              prefix={<LockOutlined />} 
              placeholder="密码" 
              size="large"
            />
          </Form.Item>

          <Form.Item>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Form.Item name="remember" valuePropName="checked" noStyle>
                <Checkbox>记住我</Checkbox>
              </Form.Item>
              <Link href="/forgot-password" style={{ color: '#1890ff' }}>
                忘记密码？
              </Link>
            </div>
          </Form.Item>

          <Form.Item>
            <Button 
              type="primary" 
              htmlType="submit" 
              size="large" 
              block 
              loading={loading}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <Divider />

        <div style={{ textAlign: 'center' }}>
          <Text type="secondary">
            还没有账号？ 
            <Link href="/register" style={{ marginLeft: '8px' }}>
              立即注册
            </Link>
          </Text>
        </div>
      </Card>
    </div>
  )
}